<!DOCTYPE html>


<html lang="zh-Hans">


<head>
  <meta charset="utf-8" />
   
  <meta name="keywords" content="代码,生活,杂记,思考" />
   
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
  <title>
    深入浅出-Webpack学习笔记（二） |  AURORA
  </title>
  <meta name="generator" content="hexo-theme-ayer">
  
  <link rel="shortcut icon" href="/favicon.ico" />
  
  
<link rel="stylesheet" href="/dist/main.css">

  
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/Shen-Yu/cdn/css/remixicon.min.css">

  
<link rel="stylesheet" href="/css/custom.css">

  
  
<script src="https://cdn.jsdelivr.net/npm/pace-js@1.0.2/pace.min.js"></script>

  
  

  

<link rel="alternate" href="/atom.xml" title="AURORA" type="application/atom+xml">
</head>

</html>

<body>
  <div id="app">
    
      
    <main class="content on">
      <section class="outer">
  <article
  id="post-深入浅出-Webpack学习笔记（二）"
  class="article article-type-post"
  itemscope
  itemprop="blogPost"
  data-scroll-reveal
>
  <div class="article-inner">
    
    <header class="article-header">
       
<h1 class="article-title sea-center" style="border-left:0" itemprop="name">
  深入浅出-Webpack学习笔记（二）
</h1>
 

    </header>
     
    <div class="article-meta">
      <a href="/2020/07/30/%E6%B7%B1%E5%85%A5%E6%B5%85%E5%87%BA-Webpack%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0%EF%BC%88%E4%BA%8C%EF%BC%89/" class="article-date">
  <time datetime="2020-07-29T16:00:00.000Z" itemprop="datePublished">2020-07-30 00:07:00</time>
</a> 
  <div class="article-category">
    <a class="article-category-link" href="/categories/%E6%8A%80%E6%9C%AF/">技术</a> / <a class="article-category-link" href="/categories/%E6%8A%80%E6%9C%AF/%E5%89%8D%E7%AB%AF/">前端</a> / <a class="article-category-link" href="/categories/%E6%8A%80%E6%9C%AF/%E5%89%8D%E7%AB%AF/webpack/">webpack</a>
  </div>
  
<div class="word_count">
    <span class="post-time">
        <span class="post-meta-item-icon">
            <i class="ri-quill-pen-line"></i>
            <span class="post-meta-item-text"> Word count:</span>
            <span class="post-count">9.6k</span>
        </span>
    </span>

    <span class="post-time">
        &nbsp; | &nbsp;
        <span class="post-meta-item-icon">
            <i class="ri-book-open-line"></i>
            <span class="post-meta-item-text"> Reading time≈</span>
            <span class="post-count">37 min</span>
        </span>
    </span>
</div>
 
    </div>
      
    <div class="tocbot"></div>




  
    <div class="article-entry" itemprop="articleBody">
       
  <p>配置 Webpack 的方式有两种：</p>
<ul>
<li>通过一个 JavaScript 文件描述配置，例如使用 webpack.config.js 文件里的配置；</li>
<li>执行 Webpack 可执行文件时通过命令行参数传入，例如 webpack –devtool source-map。</li>
</ul>
<p>这两种方式可以相互搭配，例如执行 Webpack 时通过命令 webpack –config webpack-dev.config.js 指定配置文件，再去 webpack-dev.config.js 文件里描述部分配置。</p>
<p>按照配置方式来划分，可分为：</p>
<ul>
<li>只能通过命令行参数传入的选项，这种最为少见；</li>
<li>只能通过配置文件配置的选项；</li>
<li>通过两种方式都可以配置的选项。<a id="more"></a>
</li>
</ul>
<p>以vueJs举例，vue-cli脚手架搭建的项目开发者几乎感受不到webpack的存在，因为脚手架工具已经为我们做好了最佳的配置，就算有一些个性化的配置需求，我们也只需要在vue.config.js中进行这样的配置：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">module</span>.exports = &#123;</span><br><span class="line">    configureWebpack: &#123;</span><br><span class="line">        resolve: &#123;</span><br><span class="line">            alias: &#123;</span><br><span class="line">                <span class="string">'@'</span>: path.join(__dirname, <span class="string">'src'</span>),</span><br><span class="line">            &#125;,</span><br><span class="line">        &#125;,</span><br><span class="line">    &#125;,</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<p>最终vue会将这个配置合并到webpack的配置文件当中，开发者不会直接接触并操作webpack的配置文件</p>
<p>但是现在由于学习需要，我们可以导出vue的webpack配置文件，方便我们理解webpack各个配置项，在对比的过程中深入理解各个配置的作用。</p>
<p>在vue项目的根目录下面执行：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">vue inspect &gt; output.js</span><br></pre></td></tr></table></figure>
<p>这样在根目录下就会出现一个output.js文件，这就是当前vue项目的webpack相关配置。</p>
<h1 id="Entry的配置"><a href="#Entry的配置" class="headerlink" title="Entry的配置"></a>Entry的配置</h1><p>entry是配置模块的入口，可抽象成输入，Webpack 执行构建的第一步将从入口开始搜寻及递归解析出所有入口依赖的模块。</p>
<p>entry 配置是必填的，若不填则将导致 Webpack 报错退出。</p>
<h2 id="context"><a href="#context" class="headerlink" title="context"></a>context</h2><p>Webpack 在寻找相对路径的文件时会以 context 为根目录，context 默认为执行启动 Webpack 时所在的当前工作目录。 如果想改变 context 的默认配置，则可以在配置文件里这样设置它：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">module</span>.exports = &#123;</span><br><span class="line">  context: path.resolve(__dirname, <span class="string">'app'</span>)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>注意， context 必须是一个绝对路径的字符串。 除此之外，还可以通过在启动 Webpack 时带上参数 webpack –context 来设置 context。</p>
<p>之所以在这里先介绍 context，是因为 Entry 的路径和其依赖的模块的路径可能采用相对于 context 的路径来描述，context 会影响到这些相对路径所指向的真实文件。</p>
<h2 id="Entry-类型"><a href="#Entry-类型" class="headerlink" title="Entry 类型"></a>Entry 类型</h2><p>Entry 类型可以是以下三种中的一种或者相互组合：</p>
<p><img src="https://img-blog.csdnimg.cn/20200728184720338.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3UwMTIwMzE5NTg=,size_16,color_FFFFFF,t_70" alt=""><br>如果是 array 类型，则搭配 output.library 配置项使用时，<strong>只有数组里的最后一个入口文件的模块会被导出</strong>。</p>
<h2 id="Chunk-名称"><a href="#Chunk-名称" class="headerlink" title="Chunk 名称"></a>Chunk 名称</h2><p>Webpack 会为每个生成的 Chunk 取一个名称，Chunk 的名称和 Entry 的配置有关：</p>
<ul>
<li>如果 entry 是一个 string 或 array，就只会生成一个 Chunk，这时 Chunk 的名称是 main；</li>
<li>如果 entry 是一个 object，就可能会出现多个 Chunk，这时 Chunk 的名称是 object 键值对里键的名称。</li>
</ul>
<h2 id="配置动态-Entry"><a href="#配置动态-Entry" class="headerlink" title="配置动态 Entry"></a>配置动态 Entry</h2><p>假如项目里有多个页面需要为每个页面的入口配置一个 Entry ，但这些页面的数量可能会不断增长，则这时 Entry 的配置会受到到其他因素的影响导致不能写成静态的值。其解决方法是把 Entry 设置成一个函数去动态返回上面所说的配置，代码如下：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 同步函数</span></span><br><span class="line">entry: <span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">  <span class="keyword">return</span> &#123;</span><br><span class="line">    a:<span class="string">'./pages/a'</span>,</span><br><span class="line">    b:<span class="string">'./pages/b'</span>,</span><br><span class="line">  &#125;</span><br><span class="line">&#125;;</span><br><span class="line"><span class="comment">// 异步函数</span></span><br><span class="line">entry: <span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve</span>)=&gt;</span>&#123;</span><br><span class="line">    resolve(&#123;</span><br><span class="line">       a:<span class="string">'./pages/a'</span>,</span><br><span class="line">       b:<span class="string">'./pages/b'</span>,</span><br><span class="line">    &#125;);</span><br><span class="line">  &#125;);</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<h1 id="Output配置"><a href="#Output配置" class="headerlink" title="Output配置"></a>Output配置</h1><p>output 配置如何输出最终想要的代码。output 是一个 object，里面包含一系列配置项，下面分别介绍它们。</p>
<h2 id="filename"><a href="#filename" class="headerlink" title="filename"></a>filename</h2><p>output.filename 配置输出文件的名称，为string 类型。 如果只有一个输出文件，则可以把它写成静态不变的：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">filename: <span class="string">'bundle.js'</span></span><br></pre></td></tr></table></figure>
<p>但是在有多个 Chunk 要输出时，就需要借助模版和变量了。前面说到 Webpack 会为每个 Chunk取一个名称，可以根据 Chunk 的名称来区分输出的文件名：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">filename: <span class="string">'[name].js'</span></span><br></pre></td></tr></table></figure>
<p>代码里的 [name] 代表用内置的 name 变量去替换[name]，这时你可以把它看作一个字符串模块函数， 每个要输出的 Chunk 都会通过这个函数去拼接出输出的文件名称。</p>
<p>内置变量除了 name 还包括：</p>
<p>变量名    含义</p>
<ul>
<li>id Chunk 的唯一标识，从0开始</li>
<li>name    Chunk 的名称</li>
<li>hash    Chunk 的唯一标识的 Hash 值</li>
<li>chunkhash    Chunk 内容的 Hash 值<br>其中 hash 和 chunkhash 的长度是可指定的，[hash:8] 代表取8位 Hash 值，默认是20位。</li>
</ul>
<blockquote>
<p>注意 ExtractTextWebpackPlugin 插件是使用 contenthash 来代表哈希值而不是 chunkhash，原因在于 ExtractTextWebpackPlugin 提取出来的内容是代码内容本身而不是由一组模块组成的 Chunk。</p>
</blockquote>
<h2 id="chunkFilename"><a href="#chunkFilename" class="headerlink" title="chunkFilename"></a>chunkFilename</h2><p>output.chunkFilename 配置<strong>无入口</strong>的 Chunk 在输出时的文件名称。 chunkFilename 和上面的 filename 非常类似，但 chunkFilename 只用于指定在运行过程中生成的 Chunk 在输出时的文件名称。 常见的会在运行时生成 Chunk 场景有在使用 CommonChunkPlugin、使用 import(‘path/to/module’) 动态加载等时。 chunkFilename 支持和 filename 一致的内置变量。</p>
<h2 id="path"><a href="#path" class="headerlink" title="path"></a>path</h2><p>output.path 配置输出文件存放在本地的目录，必须是 string 类型的绝对路径。通常通过 Node.js 的 path 模块去获取绝对路径：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">path: path.resolve(__dirname, <span class="string">'dist_[hash]'</span>)</span><br></pre></td></tr></table></figure>
<h2 id="publicPath"><a href="#publicPath" class="headerlink" title="publicPath"></a>publicPath</h2><p>在复杂的项目里可能会有一些构建出的资源需要异步加载，加载这些异步资源需要对应的 URL 地址。</p>
<p>output.publicPath 配置发布到线上资源的 URL 前缀，为string 类型。 默认值是空字符串 ‘’，即使用相对路径。</p>
<p>这样说可能有点抽象，举个例子，需要把构建出的资源文件上传到 CDN 服务上，以利于加快页面的打开速度。配置代码如下：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">filename:<span class="string">'[name]_[chunkhash:8].js'</span></span><br><span class="line">publicPath: <span class="string">'https://cdn.example.com/assets/'</span></span><br></pre></td></tr></table></figure>
<p>这时发布到线上的 HTML 在引入 JavaScript 文件时就需要：</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">src</span>=<span class="string">'https://cdn.example.com/assets/a_12345678.js'</span>&gt;</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p>使用该配置项时要小心，稍有不慎将导致资源加载404错误。</p>
<blockquote>
<p>当项目里使用了一些静态资源文件，比如图片啥的，为了防止打包后资源加载出错也需要设置这一项，将路径设置为打包完成后静态资源存放的目录</p>
</blockquote>
<p>output.path 和 output.publicPath 都支持字符串模版，<strong>内置变量只有一个：hash 代表一次编译操作的 Hash 值。</strong></p>
<h2 id="crossOriginLoading"><a href="#crossOriginLoading" class="headerlink" title="crossOriginLoading"></a>crossOriginLoading</h2><p>Webpack 输出的部分代码块可能需要异步加载，而异步加载是通过 JSONP 方式实现的。 JSONP 的原理是动态地向 HTML 中插入一个 <code>&lt;script src=&quot;url&quot;&gt;&lt;/script&gt;</code>标签去加载异步资源。 output.crossOriginLoading 则是用于配置这个异步插入的标签的 crossorigin 值。</p>
<p>script 标签的 crossorigin 属性可以取以下值：</p>
<ul>
<li>anonymous(默认) 在加载此脚本资源时不会带上用户的 Cookies；</li>
<li>use-credentials 在加载此脚本资源时会带上用户的 Cookies。</li>
</ul>
<p><strong>通常用设置 crossorigin 来获取异步加载的脚本执行时的详细错误信息。</strong></p>
<h2 id="libraryTarget-和-library"><a href="#libraryTarget-和-library" class="headerlink" title="libraryTarget 和 library"></a>libraryTarget 和 library</h2><p>当用 Webpack 去构建一个可以被其他模块导入使用的库时需要用到它们。</p>
<ul>
<li>output.libraryTarget 配置以何种方式导出库。</li>
<li>output.library 配置导出库的名称。</li>
</ul>
<p>它们通常搭配在一起使用。</p>
<p>output.libraryTarget 是字符串的枚举类型，支持以下配置。</p>
<h3 id="var-默认"><a href="#var-默认" class="headerlink" title="var (默认)"></a>var (默认)</h3><p>编写的库将通过 var 被赋值给通过 library 指定名称的变量。</p>
<p>假如配置了 output.library=’LibraryName’，则输出和使用的代码如下：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Webpack 输出的代码</span></span><br><span class="line"><span class="keyword">var</span> LibraryName = lib_code;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 使用库的方法</span></span><br><span class="line">LibraryName.doSomething();</span><br></pre></td></tr></table></figure>
<p>假如 output.library 为空，则将直接输出：lib_code</p>
<p>其中 lib_code 代指导出库的代码内容，是有返回值的一个自执行函数。</p>
<h3 id="commonjs"><a href="#commonjs" class="headerlink" title="commonjs"></a>commonjs</h3><p>编写的库将通过 CommonJS 规范导出。</p>
<p>假如配置了 output.library=’LibraryName’，则输出和使用的代码如下：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Webpack 输出的代码</span></span><br><span class="line">exports[<span class="string">'LibraryName'</span>] = lib_code;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 使用库的方法</span></span><br><span class="line"><span class="built_in">require</span>(<span class="string">'library-name-in-npm'</span>)[<span class="string">'LibraryName'</span>].doSomething();</span><br></pre></td></tr></table></figure>
<p>其中 library-name-in-npm 是指模块发布到 Npm 代码仓库时的名称。</p>
<h3 id="commonjs2"><a href="#commonjs2" class="headerlink" title="commonjs2"></a>commonjs2</h3><p>编写的库将通过 CommonJS2 规范导出，输出和使用的代码如下：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Webpack 输出的代码</span></span><br><span class="line"><span class="built_in">module</span>.exports = lib_code;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 使用库的方法</span></span><br><span class="line"><span class="built_in">require</span>(<span class="string">'library-name-in-npm'</span>).doSomething();</span><br></pre></td></tr></table></figure>
<p>CommonJS2 和 CommonJS 规范很相似，差别在于 CommonJS 只能用 exports 导出，而 CommonJS2 在 CommonJS 的基础上增加了 module.exports 的导出方式。</p>
<p><strong>在 output.libraryTarget 为 commonjs2 时，配置 output.library 将没有意义。</strong></p>
<h3 id="this"><a href="#this" class="headerlink" title="this"></a>this</h3><p>编写的库将通过 this 被赋值给通过 library 指定的名称，输出和使用的代码如下：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Webpack 输出的代码</span></span><br><span class="line"><span class="keyword">this</span>[<span class="string">'LibraryName'</span>] = lib_code;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 使用库的方法</span></span><br><span class="line"><span class="keyword">this</span>.LibraryName.doSomething();</span><br></pre></td></tr></table></figure>
<h3 id="window"><a href="#window" class="headerlink" title="window"></a>window</h3><p>编写的库将通过 window 被赋值给通过 library 指定的名称，即把库挂载到 window 上，输出和使用的代码如下：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Webpack 输出的代码</span></span><br><span class="line"><span class="built_in">window</span>[<span class="string">'LibraryName'</span>] = lib_code;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 使用库的方法</span></span><br><span class="line"><span class="built_in">window</span>.LibraryName.doSomething();</span><br></pre></td></tr></table></figure>
<h3 id="global"><a href="#global" class="headerlink" title="global"></a>global</h3><p>编写的库将通过 global 被赋值给通过 library 指定的名称，即把库挂载到 global 上，输出和使用的代码如下：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Webpack 输出的代码</span></span><br><span class="line">global[<span class="string">'LibraryName'</span>] = lib_code;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 使用库的方法</span></span><br><span class="line">global.LibraryName.doSomething();</span><br></pre></td></tr></table></figure>
<h2 id="libraryExport"><a href="#libraryExport" class="headerlink" title="libraryExport"></a>libraryExport</h2><p>output.libraryExport 配置要导出的模块中哪些子模块需要被导出。 <strong>它只有在 output.libraryTarget 被设置成 commonjs 或者 commonjs2 时使用才有意义。</strong></p>
<p>假如要导出的模块源代码是：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> a=<span class="number">1</span>;</span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> b=<span class="number">2</span>;</span><br></pre></td></tr></table></figure>
<p>现在你想让构建输出的代码只导出其中的 a，可以把 output.libraryExport 设置成 a，那么构建输出的代码和使用方法将变成如下：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Webpack 输出的代码</span></span><br><span class="line"><span class="built_in">module</span>.exports = lib_code[<span class="string">'a'</span>];</span><br><span class="line"></span><br><span class="line"><span class="comment">// 使用库的方法</span></span><br><span class="line"><span class="built_in">require</span>(<span class="string">'library-name-in-npm'</span>)===<span class="number">1</span>;</span><br></pre></td></tr></table></figure>
<h1 id="Module配置"><a href="#Module配置" class="headerlink" title="Module配置"></a>Module配置</h1><p>配置如何处理模块</p>
<h2 id="配置-Loader"><a href="#配置-Loader" class="headerlink" title="配置 Loader"></a>配置 Loader</h2><p>rules 配置模块的读取和解析规则，通常用来配置 Loader。其类型是一个数组，数组里每一项都描述了如何去处理部分文件。 配置一项 rules 时大致通过以下方式：</p>
<ul>
<li>条件匹配：通过 test 、 include 、 exclude 三个配置项来命中 Loader 要应用规则的文件。</li>
<li>应用规则：对选中后的文件通过 use 配置项来应用 Loader，可以只应用一个 Loader 或者按照从后往前的顺序应用一组 Loader，同时还可以分别给 Loader 传入参数。</li>
<li>重置顺序：一组 Loader 的执行顺序默认是从右到左执行，通过 enforce 选项可以让其中一个 Loader 的执行顺序放到最前或者最后。</li>
</ul>
<p>下面来通过一个例子来说明具体使用方法：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">module</span>: &#123;</span><br><span class="line">  rules: [</span><br><span class="line">    &#123;</span><br><span class="line">      <span class="comment">// 命中 JavaScript 文件</span></span><br><span class="line">      test: <span class="regexp">/\.js$/</span>,</span><br><span class="line">      <span class="comment">// 用 babel-loader 转换 JavaScript 文件</span></span><br><span class="line">      <span class="comment">// ?cacheDirectory 表示传给 babel-loader 的参数，用于缓存 babel 编译结果加快重新编译速度</span></span><br><span class="line">      use: [<span class="string">'babel-loader?cacheDirectory'</span>],</span><br><span class="line">      <span class="comment">// 只命中src目录里的js文件，加快 Webpack 搜索速度</span></span><br><span class="line">      include: path.resolve(__dirname, <span class="string">'src'</span>)</span><br><span class="line">    &#125;,</span><br><span class="line">    &#123;</span><br><span class="line">      <span class="comment">// 命中 SCSS 文件</span></span><br><span class="line">      test: <span class="regexp">/\.scss$/</span>,</span><br><span class="line">      <span class="comment">// 使用一组 Loader 去处理 SCSS 文件。</span></span><br><span class="line">      <span class="comment">// 处理顺序为从后到前，即先交给 sass-loader 处理，再把结果交给 css-loader 最后再给 style-loader。</span></span><br><span class="line">      use: [<span class="string">'style-loader'</span>, <span class="string">'css-loader'</span>, <span class="string">'sass-loader'</span>],</span><br><span class="line">      <span class="comment">// 排除 node_modules 目录下的文件</span></span><br><span class="line">      exclude: path.resolve(__dirname, <span class="string">'node_modules'</span>),</span><br><span class="line">    &#125;,</span><br><span class="line">    &#123;</span><br><span class="line">      <span class="comment">// 对非文本文件采用 file-loader 加载</span></span><br><span class="line">      test: <span class="regexp">/\.(gif|png|jpe?g|eot|woff|ttf|svg|pdf)$/</span>,</span><br><span class="line">      use: [<span class="string">'file-loader'</span>],</span><br><span class="line">    &#125;,</span><br><span class="line">  ]</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>在 Loader 需要传入很多参数时，你还可以通过一个 Object 来描述，例如在上面的 babel-loader 配置中有如下代码：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">use: [</span><br><span class="line">  &#123;</span><br><span class="line">    loader:<span class="string">'babel-loader'</span>,</span><br><span class="line">    options:&#123;</span><br><span class="line">      cacheDirectory:<span class="literal">true</span>,</span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="comment">// enforce:'post' 的含义是把该 Loader 的执行顺序放到最后</span></span><br><span class="line">    <span class="comment">// enforce 的值还可以是 pre，代表把 Loader 的执行顺序放到最前面</span></span><br><span class="line">    enforce:<span class="string">'post'</span></span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="comment">// 省略其它 Loader</span></span><br><span class="line">]</span><br></pre></td></tr></table></figure>
<p>上面的例子中 test include exclude 这三个命中文件的配置项只传入了一个字符串或正则，其实它们还都支持数组类型，使用如下：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">  test:[</span><br><span class="line">    /\.jsx?$/,</span><br><span class="line">    /\.tsx?$/</span><br><span class="line">  ],</span><br><span class="line">  include:[</span><br><span class="line">    path.resolve(__dirname, <span class="string">'src'</span>),</span><br><span class="line">    path.resolve(__dirname, <span class="string">'tests'</span>),</span><br><span class="line">  ],</span><br><span class="line">  exclude:[</span><br><span class="line">    path.resolve(__dirname, <span class="string">'node_modules'</span>),</span><br><span class="line">    path.resolve(__dirname, <span class="string">'bower_modules'</span>),</span><br><span class="line">  ]</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>数组里的每项之间是或的关系</strong>，即文件路径符合数组中的任何一个条件就会被命中。</p>
<h2 id="noParse"><a href="#noParse" class="headerlink" title="noParse"></a>noParse</h2><p>noParse 配置项可以让 Webpack 忽略对部分没采用模块化的文件的递归解析和处理，这样做的好处是能提高构建性能。 原因是一些库例如 jQuery 、ChartJS 它们庞大又没有采用模块化标准，让 Webpack 去解析这些文件耗时又没有意义。</p>
<p>noParse 是可选配置项，类型需要是 RegExp、[RegExp]、function 其中一个。</p>
<p>例如想要忽略掉 jQuery 、ChartJS，可以使用如下代码：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 使用正则表达式</span></span><br><span class="line">noParse: <span class="regexp">/jquery|chartjs/</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 使用函数，从 Webpack 3.0.0 开始支持</span></span><br><span class="line">noParse: <span class="function">(<span class="params">content</span>)=&gt;</span> &#123;</span><br><span class="line">  <span class="comment">// content 代表一个模块的文件路径</span></span><br><span class="line">  <span class="comment">// 返回 true or false</span></span><br><span class="line">  <span class="keyword">return</span> <span class="regexp">/jquery|chartjs/</span>.test(content);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>注意被忽略掉的文件里不应该包含 import 、 require 、 define 等模块化语句，不然会导致构建出的代码中包含无法在浏览器环境下执行的模块化语句。</p>
<h2 id="parser"><a href="#parser" class="headerlink" title="parser"></a>parser</h2><p>因为 Webpack 是以模块化的 JavaScript 文件为入口，所以内置了对模块化 JavaScript 的解析功能，支持 AMD、CommonJS、SystemJS、ES6。 parser 属性可以更细粒度的配置哪些模块语法要解析哪些不解析，和 noParse 配置项的区别在于 parser 可以精确到语法层面， 而 noParse 只能控制哪些文件不被解析。 parser 使用如下：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">module</span>: &#123;</span><br><span class="line">  rules: [</span><br><span class="line">    &#123;</span><br><span class="line">      test: <span class="regexp">/\.js$/</span>,</span><br><span class="line">      use: [<span class="string">'babel-loader'</span>],</span><br><span class="line">      parser: &#123;</span><br><span class="line">	      amd: <span class="literal">false</span>, <span class="comment">// 禁用 AMD</span></span><br><span class="line">	      commonjs: <span class="literal">false</span>, <span class="comment">// 禁用 CommonJS</span></span><br><span class="line">	      system: <span class="literal">false</span>, <span class="comment">// 禁用 SystemJS</span></span><br><span class="line">	      harmony: <span class="literal">false</span>, <span class="comment">// 禁用 ES6 import/export</span></span><br><span class="line">	      requireInclude: <span class="literal">false</span>, <span class="comment">// 禁用 require.include</span></span><br><span class="line">	      requireEnsure: <span class="literal">false</span>, <span class="comment">// 禁用 require.ensure</span></span><br><span class="line">	      requireContext: <span class="literal">false</span>, <span class="comment">// 禁用 require.context</span></span><br><span class="line">	      browserify: <span class="literal">false</span>, <span class="comment">// 禁用 browserify</span></span><br><span class="line">	      requireJs: <span class="literal">false</span>, <span class="comment">// 禁用 requirejs</span></span><br><span class="line">      &#125;</span><br><span class="line">    &#125;,</span><br><span class="line">  ]</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h1 id="Resolve配置"><a href="#Resolve配置" class="headerlink" title="Resolve配置"></a>Resolve配置</h1><p>Webpack 在启动后会从配置的入口模块出发找出所有依赖的模块，Resolve 配置 Webpack 如何寻找模块所对应的文件。 Webpack 内置 JavaScript 模块化语法解析功能，默认会采用模块化标准里约定好的规则去寻找，但你也可以根据自己的需要修改默认的规则。</p>
<h2 id="alias"><a href="#alias" class="headerlink" title="alias"></a>alias</h2><p>resolve.alias 配置项通过别名来把原导入路径映射成一个新的导入路径。例如使用以下配置：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Webpack alias 配置</span></span><br><span class="line">resolve:&#123;</span><br><span class="line">  alias:&#123;</span><br><span class="line">    components: <span class="string">'./src/components/'</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当你通过 import Button from ‘components/button’ 导入时，实际上被 alias 等价替换成了 import Button from ‘./src/components/button’。</p>
<p>以上 alias 配置的含义是把导入语句里的 components 关键字替换成 ./src/components/。</p>
<p>这样做可能会命中太多的导入语句，alias 还支持 $ 符号来缩小范围到只命中以关键字结尾的导入语句：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">resolve:&#123;</span><br><span class="line">  alias:&#123;</span><br><span class="line">    <span class="string">'react$'</span>: <span class="string">'/path/to/react.min.js'</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>react$ 只会命中以 react 结尾的导入语句，即只会把<code>import &#39;react&#39;</code>关键字替换成 <code>import &#39;/path/to/react.min.js&#39;</code>。</p>
<h2 id="mainFields"><a href="#mainFields" class="headerlink" title="mainFields"></a>mainFields</h2><p>有一些第三方模块会针对不同环境提供几分代码。 例如分别提供采用 ES5 和 ES6 的2份代码，这2份代码的位置写在 package.json 文件里，如下：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">  <span class="string">"jsnext:main"</span>: <span class="string">"es/index.js"</span>,<span class="comment">// 采用 ES6 语法的代码入口文件</span></span><br><span class="line">  <span class="string">"main"</span>: <span class="string">"lib/index.js"</span> <span class="comment">// 采用 ES5 语法的代码入口文件</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>Webpack 会根据 mainFields 的配置去决定优先采用那份代码，mainFields 默认如下：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">mainFields: [<span class="string">'browser'</span>, <span class="string">'main'</span>]</span><br></pre></td></tr></table></figure>
<p>Webpack 会按照数组里的顺序去package.json 文件里寻找，只会使用找到的第一个。</p>
<p>假如你想优先采用 ES6 的那份代码，可以这样配置：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">mainFields: [<span class="string">'jsnext:main'</span>, <span class="string">'browser'</span>, <span class="string">'main'</span>]</span><br></pre></td></tr></table></figure>
<h2 id="extensions"><a href="#extensions" class="headerlink" title="extensions"></a>extensions</h2><p>在导入语句没带文件后缀时，Webpack 会自动带上后缀后去尝试访问文件是否存在。 resolve.extensions 用于配置在尝试过程中用到的后缀列表，默认是：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">extensions: [<span class="string">'.js'</span>, <span class="string">'.json'</span>]</span><br></pre></td></tr></table></figure>
<p>也就是说当遇到 require(‘./data’) 这样的导入语句时，Webpack 会先去寻找 ./data.js 文件，如果该文件不存在就去寻找 ./data.json 文件， 如果还是找不到就报错。</p>
<p>假如你想让 Webpack 优先使用目录下的 TypeScript 文件，可以这样配置：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">extensions: [<span class="string">'.ts'</span>, <span class="string">'.js'</span>, <span class="string">'.json'</span>]</span><br></pre></td></tr></table></figure>
<h2 id="modules"><a href="#modules" class="headerlink" title="modules"></a>modules</h2><p>resolve.modules 配置 Webpack 去哪些目录下寻找第三方模块，默认是只会去 node_modules 目录下寻找。 有时你的项目里会有一些模块会大量被其它模块依赖和导入，由于其它模块的位置分布不定，针对不同的文件都要去计算被导入模块文件的相对路径， 这个路径有时候会很长，就像这样 <code>import &#39;../../../components/button&#39;</code>这时你可以利用 modules 配置项优化，假如那些被大量导入的模块都在<code>./src/components</code>目录下，把 modules 配置成</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">modules:[<span class="string">'./src/components'</span>,<span class="string">'node_modules'</span>]</span><br></pre></td></tr></table></figure>
<p>后，你可以简单通过 import ‘button’ 导入，这样webpack就会依次到./src/components和node_modules寻找button这个模块。</p>
<blockquote>
<p>resolve.modules是用来设置模块搜索的目录，设定目录以后，import模块路径，就可以从一个子目录开始写，这样就可以缩短模块引入路径。例如：resolve:{modules:[‘./src/components’]}则引入src下的components下的utils模块，就可以import’utils’这样就可以省略前面的src/components路径，作用是省略路径书写，让webpack自己查找<br>而resolve.alias则是给路径设置别名，作用是用别名代替前面的路径，不是省略，而是用别名代替前面的长路径。这样其实有个好处，就是webpack直接会去别名对应的目录去查找模块，减少了webpack自己去按目录查找模块的时间。例如:resolve：{alias:{‘com’:’./src/components’}}引入utils模块，就可以这样写import’com/utils’也达到了缩短引入路径的目的，写法与resolve.modules略有不同。</p>
</blockquote>
<h2 id="descriptionFiles"><a href="#descriptionFiles" class="headerlink" title="descriptionFiles"></a>descriptionFiles</h2><p>resolve.descriptionFiles 配置描述第三方模块的文件名称，也就是 package.json 文件。默认如下：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">descriptionFiles: [<span class="string">'package.json'</span>]</span><br></pre></td></tr></table></figure>
<h2 id="enforceExtension"><a href="#enforceExtension" class="headerlink" title="enforceExtension"></a>enforceExtension</h2><p>resolve.enforceExtension 如果配置为 true 所有导入语句都必须要带文件后缀， 例如开启前 import ‘./foo’ 能正常工作，开启后就必须写成 import ‘./foo.js’。</p>
<h2 id="enforceModuleExtension"><a href="#enforceModuleExtension" class="headerlink" title="enforceModuleExtension"></a>enforceModuleExtension</h2><p>enforceModuleExtension 和 enforceExtension 作用类似，但 enforceModuleExtension 只对 node_modules 下的模块生效。 enforceModuleExtension 通常搭配 enforceExtension 使用，在 enforceExtension:true 时，因为安装的第三方模块中大多数导入语句没带文件后缀， 所以这时通过配置 enforceModuleExtension:false 来兼容第三方模块。</p>
<h1 id="plugin"><a href="#plugin" class="headerlink" title="plugin"></a>plugin</h1><p>Plugin 用于扩展 Webpack 功能，各种各样的 Plugin 几乎让 Webpack 可以做任何构建相关的事情。</p>
<h2 id="配置-Plugin"><a href="#配置-Plugin" class="headerlink" title="配置 Plugin"></a>配置 Plugin</h2><p>Plugin 的配置很简单，plugins 配置项接受一个数组，数组里每一项都是一个要使用的 Plugin 的实例，Plugin 需要的参数通过构造函数传入。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> CommonsChunkPlugin = <span class="built_in">require</span>(<span class="string">'webpack/lib/optimize/CommonsChunkPlugin'</span>);</span><br><span class="line"></span><br><span class="line"><span class="built_in">module</span>.exports = &#123;</span><br><span class="line">  plugins: [</span><br><span class="line">    <span class="comment">// 所有页面都会用到的公共代码提取到 common 代码块中</span></span><br><span class="line">    <span class="keyword">new</span> CommonsChunkPlugin(&#123;</span><br><span class="line">      name: <span class="string">'common'</span>,</span><br><span class="line">      chunks: [<span class="string">'a'</span>, <span class="string">'b'</span>]</span><br><span class="line">    &#125;),</span><br><span class="line">  ]</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<p>使用 Plugin 的难点在于掌握 <strong>Plugin 本身提供的配置项</strong>，而不是如何在 Webpack 中接入 Plugin。</p>
<p>几乎所有 Webpack 无法直接实现的功能都能在社区找到开源的 Plugin 去解决，你需要善于使用搜索引擎去寻找解决问题的方法。</p>
<h1 id="devServer"><a href="#devServer" class="headerlink" title="devServer"></a>devServer</h1><p>前面我们使用DevServer 介绍过用来提高开发效率的 DevServer ，它提供了一些配置项可以改变 DevServer 的默认行为。 要配置 DevServer ，除了在配置文件里通过 devServer 传入参数外，还可以通过命令行参数传入。 <strong>注意只有在通过 DevServer 去启动 Webpack 时配置文件里 devServer 才会生效</strong>，因为这些参数所对应的功能都是 DevServer 提供的，Webpack 本身并不认识 devServer 配置项。</p>
<h2 id="hot"><a href="#hot" class="headerlink" title="hot"></a>hot</h2><p>devServer.hot 配置是否启用DevServer 中提到的模块热替换功能。 DevServer 默认的行为是在发现源代码被更新后会通过<strong>自动刷新</strong>整个页面来做到实时预览，开启模块热替换功能后将在<strong>不刷新</strong>整个页面的情况下通过用新模块替换老模块来做到实时预览。</p>
<h2 id="inline"><a href="#inline" class="headerlink" title="inline"></a>inline</h2><p>DevServer 的实时预览功能依赖一个注入到页面里的代理客户端去接受来自 DevServer 的命令和负责刷新网页的工作。 devServer.inline 用于配置是否自动注入这个代理客户端到将运行在页面里的 Chunk 里去，默认是会自动注入。 DevServer 会根据你是否开启 inline 来调整它的自动刷新策略：</p>
<ul>
<li>如果开启 inline，DevServer 会在构建完变化后的代码时通过代理客户端控制网页刷新。</li>
<li>如果关闭 inline，DevServer 将无法直接控制要开发的网页。这时它会通过 iframe 的方式去运行要开发的网页，当构建完变化后的代码时通过刷新 iframe 来实现实时预览。 但这时你需要去 <a href="http://localhost:8080/webpack-dev-server/" target="_blank" rel="noopener">http://localhost:8080/webpack-dev-server/</a> 实时预览你的网页了。</li>
</ul>
<p><strong>如果你想使用 DevServer 去自动刷新网页实现实时预览，最方便的方法是直接开启 inline。</strong></p>
<h2 id="historyApiFallback"><a href="#historyApiFallback" class="headerlink" title="historyApiFallback"></a>historyApiFallback</h2><p>devServer.historyApiFallback 用于方便的开发使用了 HTML5 History API 的单页应用。 这类单页应用要求服务器在针对任何命中的路由时都返回一个对应的 HTML 文件，例如在访问 <a href="http://localhost/user" target="_blank" rel="noopener">http://localhost/user</a> 和 <a href="http://localhost/home" target="_blank" rel="noopener">http://localhost/home</a> 时都返回 index.html 文件， 浏览器端的 JavaScript 代码会从 URL 里解析出当前页面的状态，显示出对应的界面。</p>
<p>配置 historyApiFallback 最简单的做法是：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">historyApiFallback: <span class="literal">true</span></span><br></pre></td></tr></table></figure>
<p>这会导致任何请求都会返回 index.html 文件，这只能用于只有一个 HTML 文件的应用。</p>
<p>如果你的应用由多个单页应用组成，这就需要 DevServer 根据不同的请求来返回不同的 HTML 文件，配置如下：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">historyApiFallback: &#123;</span><br><span class="line">  <span class="comment">// 使用正则匹配命中路由</span></span><br><span class="line">  rewrites: [</span><br><span class="line">    <span class="comment">// /user 开头的都返回 user.html</span></span><br><span class="line">    &#123; <span class="attr">from</span>: <span class="regexp">/^\/user/</span>, <span class="attr">to</span>: <span class="string">'/user.html'</span> &#125;,</span><br><span class="line">    &#123; <span class="attr">from</span>: <span class="regexp">/^\/game/</span>, <span class="attr">to</span>: <span class="string">'/game.html'</span> &#125;,</span><br><span class="line">    <span class="comment">// 其它的都返回 index.html</span></span><br><span class="line">    &#123; <span class="attr">from</span>: <span class="regexp">/./</span>, <span class="attr">to</span>: <span class="string">'/index.html'</span> &#125;,</span><br><span class="line">  ]</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="contentBase"><a href="#contentBase" class="headerlink" title="contentBase"></a>contentBase</h2><p>devServer.contentBase 配置 DevServer HTTP 服务器的文件根目录。 默认情况下为当前执行目录，通常是项目根目录，所有一般情况下你不必设置它，除非你有额外的文件需要被 DevServer 服务。 例如你想把项目根目录下的 public 目录设置成 DevServer 服务器的文件根目录，你可以这样配置：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">devServer:&#123;</span><br><span class="line">  contentBase: path.join(__dirname, <span class="string">'public'</span>)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这里需要指出可能会让你疑惑的地方，DevServer 服务器通过 HTTP 服务暴露出的文件分为两类：</p>
<ul>
<li>暴露本地文件。</li>
<li>暴露 Webpack 构建出的结果，由于构建出的结果交给了 DevServer，所以你在使用了 DevServer 时在本地找不到构建出的文件。</li>
</ul>
<p>contentBase 只能用来配置暴露本地文件的规则，你可以通过 contentBase:false 来关闭暴露本地文件。</p>
<h2 id="headers"><a href="#headers" class="headerlink" title="headers"></a>headers</h2><p>devServer.headers 配置项可以在 HTTP 响应中注入一些 HTTP 响应头，使用如下：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">devServer:&#123;</span><br><span class="line">  headers: &#123;</span><br><span class="line">    <span class="string">'X-foo'</span>:<span class="string">'bar'</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="host"><a href="#host" class="headerlink" title="host"></a>host</h2><p>devServer.host 配置项用于配置 DevServer 服务监听的地址。 例如你想要局域网中的其它设备访问你本地的服务，可以在启动 DevServer 时带上 –host 0.0.0.0。 host 的默认值是 127.0.0.1 即只有本地可以访问 DevServer 的 HTTP 服务。</p>
<h2 id="port"><a href="#port" class="headerlink" title="port"></a>port</h2><p>devServer.port 配置项用于配置 DevServer 服务监听的端口，默认使用 8080 端口。 如果 8080 端口已经被其它程序占有就使用 8081，如果 8081 还是被占用就使用 8082，以此类推。</p>
<h2 id="allowedHosts"><a href="#allowedHosts" class="headerlink" title="allowedHosts"></a>allowedHosts</h2><p>devServer.allowedHosts 配置一个白名单列表，只有 HTTP 请求的 HOST 在列表里才正常返回，使用如下：</p>
<p>allowedHosts: [<br>  // 匹配单个域名<br>  ‘host.com’,<br>  ‘sub.host.com’,<br>  // host2.com 和所有的子域名 *.host2.com 都将匹配<br>  ‘.host2.com’<br>]</p>
<h2 id="disableHostCheck"><a href="#disableHostCheck" class="headerlink" title="disableHostCheck"></a>disableHostCheck</h2><p>devServer.disableHostCheck 配置项用于配置是否关闭用于 DNS 重绑定的 HTTP 请求的 HOST 检查。 DevServer 默认只接受来自本地的请求，关闭后可以接受来自任何 HOST 的请求。 它通常用于搭配 –host 0.0.0.0 使用，因为你想要其它设备访问你本地的服务，但访问时是直接通过 IP 地址访问而不是 HOST 访问，所以需要关闭 HOST 检查。</p>
<h2 id="https"><a href="#https" class="headerlink" title="https"></a>https</h2><p>DevServer 默认使用 HTTP 协议服务，它也能通过 HTTPS 协议服务。 有些情况下你必须使用 HTTPS，例如 HTTP2 和 Service Worker 就必须运行在 HTTPS 之上。 要切换成 HTTPS 服务，最简单的方式是：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">devServer:&#123;</span><br><span class="line">  https: <span class="literal">true</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>DevServer 会自动的为你生成一份 HTTPS 证书。</p>
<p>如果你想用自己的证书可以这样配置：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">devServer:&#123;</span><br><span class="line">  https: &#123;</span><br><span class="line">    key: fs.readFileSync(<span class="string">'path/to/server.key'</span>),</span><br><span class="line">    cert: fs.readFileSync(<span class="string">'path/to/server.crt'</span>),</span><br><span class="line">    ca: fs.readFileSync(<span class="string">'path/to/ca.pem'</span>)</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="clientLogLevel"><a href="#clientLogLevel" class="headerlink" title="clientLogLevel"></a>clientLogLevel</h2><p>devServer.clientLogLevel 配置在客户端的日志等级，这会影响到你在浏览器开发者工具控制台里看到的日志内容。 clientLogLevel 是枚举类型，可取如下之一的值 none | error | warning | info。 默认为 info 级别，即输出所有类型的日志，设置成 none 可以不输出任何日志。</p>
<h2 id="compress"><a href="#compress" class="headerlink" title="compress"></a>compress</h2><p>devServer.compress 配置是否启用 gzip 压缩。boolean 为类型，默认为 false。</p>
<h2 id="open"><a href="#open" class="headerlink" title="open"></a>open</h2><p>devServer.open 用于在 DevServer 启动且第一次构建完时自动用你系统上默认的浏览器去打开要开发的网页。 同时还提供 devServer.openPage 配置项用于打开指定 URL 的网页。</p>
<h1 id="其他配置项"><a href="#其他配置项" class="headerlink" title="其他配置项"></a>其他配置项</h1><h2 id="Target"><a href="#Target" class="headerlink" title="Target"></a>Target</h2><p>JavaScript 的应用场景越来越多，从浏览器到 Node.js，这些运行在不同环境的 JavaScript 代码存在一些差异。 target 配置项可以让 Webpack 构建出针对不同运行环境的代码。 target 可以是以下之一：<br><img src="https://img-blog.csdnimg.cn/20200730110434921.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3UwMTIwMzE5NTg=,size_16,color_FFFFFF,t_70" alt=""><br>例如当你设置 target:’node’ 时，源代码中导入 Node.js 原生模块的语句 require(‘fs’) 将会被保留，fs 模块的内容不会打包进 Chunk 里。</p>
<h2 id="DevTool"><a href="#DevTool" class="headerlink" title="DevTool"></a>DevTool</h2><p>代码生成 Source Map 以方便调试，可以这样配置：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">module</span>.export = &#123;</span><br><span class="line">  devtool: <span class="string">'source-map'</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="Watch-和-WatchOptions"><a href="#Watch-和-WatchOptions" class="headerlink" title="Watch 和 WatchOptions"></a>Watch 和 WatchOptions</h2><p>前面介绍过 Webpack 的监听模式，它支持监听文件更新，在文件发生变化时重新编译。在使用 Webpack 时监听模式默认是关闭的，想打开需要如下配置：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">module</span>.export = &#123;</span><br><span class="line">  watch: <span class="literal">true</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>在使用 DevServer 时，监听模式默认是开启的。</strong></p>
<p>除此之外，Webpack 还提供了 watchOptions 配置项去更灵活的控制监听模式，使用如下：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">module</span>.export = &#123;</span><br><span class="line">  <span class="comment">// 只有在开启监听模式时，watchOptions 才有意义</span></span><br><span class="line">  <span class="comment">// 默认为 false，也就是不开启</span></span><br><span class="line">  watch: <span class="literal">true</span>,</span><br><span class="line">  <span class="comment">// 监听模式运行时的参数</span></span><br><span class="line">  <span class="comment">// 在开启监听模式时，才有意义</span></span><br><span class="line">  watchOptions: &#123;</span><br><span class="line">    <span class="comment">// 不监听的文件或文件夹，支持正则匹配</span></span><br><span class="line">    <span class="comment">// 默认为空</span></span><br><span class="line">    ignored: <span class="regexp">/node_modules/</span>,</span><br><span class="line">    <span class="comment">// 监听到变化发生后会等300ms再去执行动作，防止文件更新太快导致重新编译频率太高</span></span><br><span class="line">    <span class="comment">// 默认为 300ms  </span></span><br><span class="line">    aggregateTimeout: <span class="number">300</span>,</span><br><span class="line">    <span class="comment">// 判断文件是否发生变化是通过不停的去询问系统指定文件有没有变化实现的</span></span><br><span class="line">    <span class="comment">// 默认每隔1000毫秒询问一次</span></span><br><span class="line">    poll: <span class="number">1000</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>上述代码中需要注意的点：</p>
<ul>
<li>监听到变化发生后默认会等300ms再去执行动作，防止文件更新太快导致重新编译频率太高</li>
<li>判断文件是否发生变化是通过不停的去询问系统指定文件有没有变化实现的，默认1000ms询问一次</li>
</ul>
<h2 id="Externals"><a href="#Externals" class="headerlink" title="Externals"></a>Externals</h2><p>Externals 用来告诉 Webpack 要构建的代码中使用了哪些不用被打包的模块，也就是说这些模版是外部环境提供的，Webpack 在打包时可以忽略它们。</p>
<p>有些 JavaScript 运行环境可能内置了一些全局变量或者模块，例如在你的 HTML HEAD 标签里通过以下代码：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&lt;script src=<span class="string">"path/to/jquery.js"</span>&gt;&lt;<span class="regexp">/script&gt;</span></span><br></pre></td></tr></table></figure>
<p>引入 jQuery 后，全局变量 jQuery 就会被注入到网页的 JavaScript 运行环境里。</p>
<p>如果想在使用模块化的源代码里导入和使用 jQuery，可能需要这样：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> $ <span class="keyword">from</span> <span class="string">'jquery'</span>;</span><br><span class="line">$(<span class="string">'.my-element'</span>);</span><br></pre></td></tr></table></figure>
<p>构建后你会发现输出的 Chunk 里包含的 jQuery 库的内容，这导致 jQuery 库出现了2次，浪费加载流量，最好是 Chunk 里不会包含 jQuery 库的内容。</p>
<p>Externals 配置项就是为了解决这个问题。</p>
<p>通过 externals 可以告诉 Webpack JavaScript 运行环境已经内置了那些全局变量，针对这些全局变量不用打包进代码中而是直接使用全局变量。 要解决以上问题，可以这样配置 externals：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">module</span>.export = &#123;</span><br><span class="line">  externals: &#123;</span><br><span class="line">    <span class="comment">// 把导入语句里的 jquery 替换成运行环境里的全局变量 jQuery</span></span><br><span class="line">    jquery: <span class="string">'jQuery'</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="ResolveLoader"><a href="#ResolveLoader" class="headerlink" title="ResolveLoader"></a>ResolveLoader</h2><p>ResolveLoader 用来告诉 Webpack 如何去寻找 Loader，因为在使用 Loader 时是通过其包名称去引用的， Webpack 需要根据配置的 Loader 包名去找到 Loader 的实际代码，以调用 Loader 去处理源文件。</p>
<p>ResolveLoader 的默认配置如下：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">module</span>.exports = &#123;</span><br><span class="line">  resolveLoader:&#123;</span><br><span class="line">    <span class="comment">// 去哪个目录下寻找 Loader</span></span><br><span class="line">    modules: [<span class="string">'node_modules'</span>],</span><br><span class="line">    <span class="comment">// 入口文件的后缀</span></span><br><span class="line">    extensions: [<span class="string">'.js'</span>, <span class="string">'.json'</span>],</span><br><span class="line">    <span class="comment">// 指明入口文件位置的字段</span></span><br><span class="line">    mainFields: [<span class="string">'loader'</span>, <span class="string">'main'</span>]</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>该配置项常用于加载本地的 Loader。</p>
<h1 id="一份整体的配置结构"><a href="#一份整体的配置结构" class="headerlink" title="一份整体的配置结构"></a>一份整体的配置结构</h1><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> path = <span class="built_in">require</span>(<span class="string">'path'</span>);</span><br><span class="line"></span><br><span class="line"><span class="built_in">module</span>.exports = &#123;</span><br><span class="line">  <span class="comment">// entry 表示 入口，Webpack 执行构建的第一步将从 Entry 开始，可抽象成输入。</span></span><br><span class="line">  <span class="comment">// 类型可以是 string | object | array   </span></span><br><span class="line">  entry: <span class="string">'./app/entry'</span>, <span class="comment">// 只有1个入口，入口只有1个文件</span></span><br><span class="line">  entry: [<span class="string">'./app/entry1'</span>, <span class="string">'./app/entry2'</span>], <span class="comment">// 只有1个入口，入口有2个文件</span></span><br><span class="line">  entry: &#123; <span class="comment">// 有2个入口</span></span><br><span class="line">    a: <span class="string">'./app/entry-a'</span>,</span><br><span class="line">    b: [<span class="string">'./app/entry-b1'</span>, <span class="string">'./app/entry-b2'</span>]</span><br><span class="line">  &#125;,</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 如何输出结果：在 Webpack 经过一系列处理后，如何输出最终想要的代码。</span></span><br><span class="line">  output: &#123;</span><br><span class="line">    <span class="comment">// 输出文件存放的目录，必须是 string 类型的绝对路径。</span></span><br><span class="line">    path: path.resolve(__dirname, <span class="string">'dist'</span>),</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 输出文件的名称</span></span><br><span class="line">    filename: <span class="string">'bundle.js'</span>, <span class="comment">// 完整的名称</span></span><br><span class="line">    filename: <span class="string">'[name].js'</span>, <span class="comment">// 当配置了多个 entry 时，通过名称模版为不同的 entry 生成不同的文件名称</span></span><br><span class="line">    filename: <span class="string">'[chunkhash].js'</span>, <span class="comment">// 根据文件内容 hash 值生成文件名称，用于浏览器长时间缓存文件</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">// 发布到线上的所有资源的 URL 前缀，string 类型</span></span><br><span class="line">    publicPath: <span class="string">'/assets/'</span>, <span class="comment">// 放到指定目录下</span></span><br><span class="line">    publicPath: <span class="string">''</span>, <span class="comment">// 放到根目录下</span></span><br><span class="line">    publicPath: <span class="string">'https://cdn.example.com/'</span>, <span class="comment">// 放到 CDN 上去</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">// 导出库的名称，string 类型</span></span><br><span class="line">    <span class="comment">// 不填它时，默认输出格式是匿名的立即执行函数</span></span><br><span class="line">    library: <span class="string">'MyLibrary'</span>,</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 导出库的类型，枚举类型，默认是 var</span></span><br><span class="line">    <span class="comment">// 可以是 umd | umd2 | commonjs2 | commonjs | amd | this | var | assign | window | global | jsonp ，</span></span><br><span class="line">    libraryTarget: <span class="string">'umd'</span>, </span><br><span class="line"></span><br><span class="line">    <span class="comment">// 是否包含有用的文件路径信息到生成的代码里去，boolean 类型</span></span><br><span class="line">    pathinfo: <span class="literal">true</span>, </span><br><span class="line"></span><br><span class="line">    <span class="comment">// 附加 Chunk 的文件名称</span></span><br><span class="line">    chunkFilename: <span class="string">'[id].js'</span>,</span><br><span class="line">    chunkFilename: <span class="string">'[chunkhash].js'</span>,</span><br><span class="line"></span><br><span class="line">    <span class="comment">// JSONP 异步加载资源时的回调函数名称，需要和服务端搭配使用</span></span><br><span class="line">    jsonpFunction: <span class="string">'myWebpackJsonp'</span>,</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 生成的 Source Map 文件名称</span></span><br><span class="line">    sourceMapFilename: <span class="string">'[file].map'</span>,</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 浏览器开发者工具里显示的源码模块名称</span></span><br><span class="line">    devtoolModuleFilenameTemplate: <span class="string">'webpack:///[resource-path]'</span>,</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 异步加载跨域的资源时使用的方式</span></span><br><span class="line">    crossOriginLoading: <span class="string">'use-credentials'</span>,</span><br><span class="line">    crossOriginLoading: <span class="string">'anonymous'</span>,</span><br><span class="line">    crossOriginLoading: <span class="literal">false</span>,</span><br><span class="line">  &#125;,</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 配置模块相关</span></span><br><span class="line">  <span class="built_in">module</span>: &#123;</span><br><span class="line">    rules: [ <span class="comment">// 配置 Loader</span></span><br><span class="line">      &#123;  </span><br><span class="line">        test: <span class="regexp">/\.jsx?$/</span>, <span class="comment">// 正则匹配命中要使用 Loader 的文件</span></span><br><span class="line">        include: [ <span class="comment">// 只会命中这里面的文件</span></span><br><span class="line">          path.resolve(__dirname, <span class="string">'app'</span>)</span><br><span class="line">        ],</span><br><span class="line">        exclude: [ <span class="comment">// 忽略这里面的文件</span></span><br><span class="line">          path.resolve(__dirname, <span class="string">'app/demo-files'</span>)</span><br><span class="line">        ],</span><br><span class="line">        use: [ <span class="comment">// 使用那些 Loader，有先后次序，从后往前执行</span></span><br><span class="line">          <span class="string">'style-loader'</span>, <span class="comment">// 直接使用 Loader 的名称</span></span><br><span class="line">          &#123;</span><br><span class="line">            loader: <span class="string">'css-loader'</span>,      </span><br><span class="line">            options: &#123; <span class="comment">// 给 html-loader 传一些参数</span></span><br><span class="line">            &#125;</span><br><span class="line">          &#125;</span><br><span class="line">        ]</span><br><span class="line">      &#125;,</span><br><span class="line">    ],</span><br><span class="line">    noParse: [ <span class="comment">// 不用解析和处理的模块</span></span><br><span class="line">      /special-library\.js$/  <span class="comment">// 用正则匹配</span></span><br><span class="line">    ],</span><br><span class="line">  &#125;,</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 配置插件</span></span><br><span class="line">  plugins: [</span><br><span class="line">  ],</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 配置寻找模块的规则</span></span><br><span class="line">  resolve: &#123; </span><br><span class="line">    modules: [ <span class="comment">// 寻找模块的根目录，array 类型，默认以 node_modules 为根目录</span></span><br><span class="line">      <span class="string">'node_modules'</span>,</span><br><span class="line">      path.resolve(__dirname, <span class="string">'app'</span>)</span><br><span class="line">    ],</span><br><span class="line">    extensions: [<span class="string">'.js'</span>, <span class="string">'.json'</span>, <span class="string">'.jsx'</span>, <span class="string">'.css'</span>], <span class="comment">// 模块的后缀名</span></span><br><span class="line">    alias: &#123; <span class="comment">// 模块别名配置，用于映射模块</span></span><br><span class="line">       <span class="comment">// 把 'module' 映射 'new-module'，同样的 'module/path/file' 也会被映射成 'new-module/path/file'</span></span><br><span class="line">      <span class="string">'module'</span>: <span class="string">'new-module'</span>,</span><br><span class="line">      <span class="comment">// 使用结尾符号 $ 后，把 'only-module' 映射成 'new-module'，</span></span><br><span class="line">      <span class="comment">// 但是不像上面的，'module/path/file' 不会被映射成 'new-module/path/file'</span></span><br><span class="line">      <span class="string">'only-module$'</span>: <span class="string">'new-module'</span>, </span><br><span class="line">    &#125;,</span><br><span class="line">    alias: [ <span class="comment">// alias 还支持使用数组来更详细的配置</span></span><br><span class="line">      &#123;</span><br><span class="line">        name: <span class="string">'module'</span>, <span class="comment">// 老的模块</span></span><br><span class="line">        alias: <span class="string">'new-module'</span>, <span class="comment">// 新的模块</span></span><br><span class="line">        <span class="comment">// 是否是只映射模块，如果是 true 只有 'module' 会被映射，如果是 false 'module/inner/path' 也会被映射</span></span><br><span class="line">        onlyModule: <span class="literal">true</span>, </span><br><span class="line">      &#125;</span><br><span class="line">    ],</span><br><span class="line">    symlinks: <span class="literal">true</span>, <span class="comment">// 是否跟随文件软链接去搜寻模块的路径</span></span><br><span class="line">    descriptionFiles: [<span class="string">'package.json'</span>], <span class="comment">// 模块的描述文件</span></span><br><span class="line">    mainFields: [<span class="string">'main'</span>], <span class="comment">// 模块的描述文件里的描述入口的文件的字段名称</span></span><br><span class="line">    enforceExtension: <span class="literal">false</span>, <span class="comment">// 是否强制导入语句必须要写明文件后缀</span></span><br><span class="line">  &#125;,</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 输出文件性能检查配置</span></span><br><span class="line">  performance: &#123; </span><br><span class="line">    hints: <span class="string">'warning'</span>, <span class="comment">// 有性能问题时输出警告</span></span><br><span class="line">    hints: <span class="string">'error'</span>, <span class="comment">// 有性能问题时输出错误</span></span><br><span class="line">    hints: <span class="literal">false</span>, <span class="comment">// 关闭性能检查</span></span><br><span class="line">    maxAssetSize: <span class="number">200000</span>, <span class="comment">// 最大文件大小 (单位 bytes)</span></span><br><span class="line">    maxEntrypointSize: <span class="number">400000</span>, <span class="comment">// 最大入口文件大小 (单位 bytes)</span></span><br><span class="line">    assetFilter: <span class="function"><span class="keyword">function</span>(<span class="params">assetFilename</span>) </span>&#123; <span class="comment">// 过滤要检查的文件</span></span><br><span class="line">      <span class="keyword">return</span> assetFilename.endsWith(<span class="string">'.css'</span>) || assetFilename.endsWith(<span class="string">'.js'</span>);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;,</span><br><span class="line"></span><br><span class="line">  devtool: <span class="string">'source-map'</span>, <span class="comment">// 配置 source-map 类型</span></span><br><span class="line"></span><br><span class="line">  context: __dirname, <span class="comment">// Webpack 使用的根目录，string 类型必须是绝对路径</span></span><br><span class="line"></span><br><span class="line">  <span class="comment">// 配置输出代码的运行环境</span></span><br><span class="line">  target: <span class="string">'web'</span>, <span class="comment">// 浏览器，默认</span></span><br><span class="line">  target: <span class="string">'webworker'</span>, <span class="comment">// WebWorker</span></span><br><span class="line">  target: <span class="string">'node'</span>, <span class="comment">// Node.js，使用 `require` 语句加载 Chunk 代码</span></span><br><span class="line">  target: <span class="string">'async-node'</span>, <span class="comment">// Node.js，异步加载 Chunk 代码</span></span><br><span class="line">  target: <span class="string">'node-webkit'</span>, <span class="comment">// nw.js</span></span><br><span class="line">  target: <span class="string">'electron-main'</span>, <span class="comment">// electron, 主线程</span></span><br><span class="line">  target: <span class="string">'electron-renderer'</span>, <span class="comment">// electron, 渲染线程</span></span><br><span class="line"></span><br><span class="line">  externals: &#123; <span class="comment">// 使用来自 JavaScript 运行环境提供的全局变量</span></span><br><span class="line">    jquery: <span class="string">'jQuery'</span></span><br><span class="line">  &#125;,</span><br><span class="line"></span><br><span class="line">  stats: &#123; <span class="comment">// 控制台输出日志控制</span></span><br><span class="line">    assets: <span class="literal">true</span>,</span><br><span class="line">    colors: <span class="literal">true</span>,</span><br><span class="line">    errors: <span class="literal">true</span>,</span><br><span class="line">    errorDetails: <span class="literal">true</span>,</span><br><span class="line">    hash: <span class="literal">true</span>,</span><br><span class="line">  &#125;,</span><br><span class="line"></span><br><span class="line">  devServer: &#123; <span class="comment">// DevServer 相关的配置</span></span><br><span class="line">    proxy: &#123; <span class="comment">// 代理到后端服务接口</span></span><br><span class="line">      <span class="string">'/api'</span>: <span class="string">'http://localhost:3000'</span></span><br><span class="line">    &#125;,</span><br><span class="line">    contentBase: path.join(__dirname, <span class="string">'public'</span>), <span class="comment">// 配置 DevServer HTTP 服务器的文件根目录</span></span><br><span class="line">    compress: <span class="literal">true</span>, <span class="comment">// 是否开启 gzip 压缩</span></span><br><span class="line">    historyApiFallback: <span class="literal">true</span>, <span class="comment">// 是否开发 HTML5 History API 网页</span></span><br><span class="line">    hot: <span class="literal">true</span>, <span class="comment">// 是否开启模块热替换功能</span></span><br><span class="line">    https: <span class="literal">false</span>, <span class="comment">// 是否开启 HTTPS 模式</span></span><br><span class="line">    &#125;,</span><br><span class="line"></span><br><span class="line">    profile: <span class="literal">true</span>, <span class="comment">// 是否捕捉 Webpack 构建的性能信息，用于分析什么原因导致构建性能不佳</span></span><br><span class="line"></span><br><span class="line">    cache: <span class="literal">false</span>, <span class="comment">// 是否启用缓存提升构建速度</span></span><br><span class="line"></span><br><span class="line">    watch: <span class="literal">true</span>, <span class="comment">// 是否开始</span></span><br><span class="line">    watchOptions: &#123; <span class="comment">// 监听模式选项</span></span><br><span class="line">    <span class="comment">// 不监听的文件或文件夹，支持正则匹配。默认为空</span></span><br><span class="line">    ignored: <span class="regexp">/node_modules/</span>,</span><br><span class="line">    <span class="comment">// 监听到变化发生后会等300ms再去执行动作，防止文件更新太快导致重新编译频率太高</span></span><br><span class="line">    <span class="comment">// 默认为300ms </span></span><br><span class="line">    aggregateTimeout: <span class="number">300</span>,</span><br><span class="line">    <span class="comment">// 判断文件是否发生变化是不停的去询问系统指定文件有没有变化，默认每隔1000毫秒询问一次</span></span><br><span class="line">    poll: <span class="number">1000</span></span><br><span class="line">  &#125;,</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h1 id="多种配置类型"><a href="#多种配置类型" class="headerlink" title="多种配置类型"></a>多种配置类型</h1><p>除了通过导出一个 Object 来描述 Webpack 所需的配置外，还有其它更灵活的方式，以简化不同场景的配置。 下面来一一介绍它们。</p>
<h2 id="导出一个-Function"><a href="#导出一个-Function" class="headerlink" title="导出一个 Function"></a>导出一个 Function</h2><p>在大多数时候你需要从同一份源代码中构建出多份代码，例如一份用于开发时，一份用于发布到线上。</p>
<p>如果采用导出一个 Object 来描述 Webpack 所需的配置的方法，需要写两个文件。 一个用于开发环境，一个用于线上环境。再在启动时通过 webpack –config webpack.config.js 指定使用哪个配置文件。</p>
<p>采用导出一个 Function 的方式，能通过 JavaScript 灵活的控制配置，做到只用写一个配置文件就能完成以上要求。</p>
<p>导出一个 Function 的使用方式如下：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> path = <span class="built_in">require</span>(<span class="string">'path'</span>);</span><br><span class="line"><span class="keyword">const</span> UglifyJsPlugin = <span class="built_in">require</span>(<span class="string">'webpack/lib/optimize/UglifyJsPlugin'</span>);</span><br><span class="line"></span><br><span class="line"><span class="built_in">module</span>.exports = <span class="function"><span class="keyword">function</span> (<span class="params">env = &#123;&#125;, argv</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> plugins = [];</span><br><span class="line"></span><br><span class="line">  <span class="keyword">const</span> isProduction = env[<span class="string">'production'</span>];</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 在生成环境才压缩</span></span><br><span class="line">  <span class="keyword">if</span> (isProduction) &#123;</span><br><span class="line">    plugins.push(</span><br><span class="line">      <span class="comment">// 压缩输出的 JS 代码</span></span><br><span class="line">      <span class="keyword">new</span> UglifyJsPlugin()</span><br><span class="line">    )</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> &#123;</span><br><span class="line">    plugins: plugins,</span><br><span class="line">    <span class="comment">// 在生成环境不输出 Source Map</span></span><br><span class="line">    devtool: isProduction ? <span class="literal">undefined</span> : <span class="string">'source-map'</span>,</span><br><span class="line">  &#125;;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>在运行 Webpack 时，会给这个函数传入2个参数，分别是：</p>
<ul>
<li>env：当前运行时的 Webpack 专属环境变量，env 是一个 Object。读取时直接访问 Object 的属性，设置它需要在启动 Webpack 时带上参数。例如启动命令是 webpack –env.production –env.bao=foo时，则 env 的值是 {“production”:”true”,”bao”:”foo”}。</li>
<li>argv：代表在启动 Webpack 时所有通过命令行传入的参数，例如 –config、–env、–devtool，可以通过 webpack -h 列出所有 Webpack 支持的命令行参数。</li>
</ul>
<p>就以上配置文件而言，在开发时执行命令 webpack 构建出方便调试的代码，在需要构建出发布到线上的代码时执行 webpack –env.production 构建出压缩的代码。</p>
<p>本实例 提供项目完整代码</p>
<p>导出一个返回 Promise 的函数<br>在有些情况下你不能以同步的方式返回一个描述配置的 Object，Webpack 还支持导出一个返回 Promise 的函数，使用如下：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">module</span>.exports = <span class="function"><span class="keyword">function</span>(<span class="params">env = &#123;&#125;, argv</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">    setTimeout(<span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">      resolve(&#123;</span><br><span class="line">        <span class="comment">// ...</span></span><br><span class="line">      &#125;)</span><br><span class="line">    &#125;, <span class="number">5000</span>)</span><br><span class="line">  &#125;)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="导出多份配置"><a href="#导出多份配置" class="headerlink" title="导出多份配置"></a>导出多份配置</h2><p>除了只导出一份配置外，Webpack 还支持导出一个数组，数组中可以包含每份配置，并且每份配置都会执行一遍构建。</p>
<p>注意本特性从 Webpack 3.1.0 版本才开始支持。</p>
<p>使用如下：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">module</span>.exports = [</span><br><span class="line">  <span class="comment">// 采用 Object 描述的一份配置</span></span><br><span class="line">  &#123;</span><br><span class="line">    <span class="comment">// ...</span></span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="comment">// 采用函数描述的一份配置</span></span><br><span class="line">  <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> &#123;</span><br><span class="line">      <span class="comment">// ...</span></span><br><span class="line">    &#125;</span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="comment">// 采用异步函数描述的一份配置</span></span><br><span class="line">  <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">Promise</span>();</span><br><span class="line">  &#125;</span><br><span class="line">]</span><br></pre></td></tr></table></figure>
<p>以上配置会导致 Webpack 针对这三份配置执行三次不同的构建。</p>
<p>这特别适合于用 Webpack 构建一个要上传到 Npm 仓库的库，因为库中可能需要包含多种模块化格式的代码，例如 CommonJS、UMD。</p>
<h1 id="配置总结"><a href="#配置总结" class="headerlink" title="配置总结"></a>配置总结</h1><p>从前面的配置看来选项很多，Webpack 内置了很多功能。 你不必都记住它们，只需要大概明白 Webpack 原理和核心概念去判断选项大致属于哪个大模块下，再去查详细的使用文档。</p>
<p>通常你可用如下经验去判断如何配置 Webpack：</p>
<ul>
<li>想让源文件加入到构建流程中去被 Webpack 控制，配置 entry。</li>
<li>想自定义输出文件的位置和名称，配置 output。</li>
<li>想自定义寻找依赖模块时的策略，配置 resolve。</li>
<li>想自定义解析和转换文件的策略，配置 module，通常是配置 module.rules 里的 Loader。</li>
<li>其它的大部分需求可能要通过 Plugin 去实现，配置 plugin。</li>
</ul>
 
      <!-- reward -->
      
    </div>
    

    <!-- copyright -->
    
    <div class="declare">
      <ul class="post-copyright">
        <li>
          <i class="ri-copyright-line"></i>
          <strong>Copyright： </strong>
          Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
        </li>
      </ul>
    </div>
    
    <footer class="article-footer">
       
<div class="share-btn">
      <span class="share-sns share-outer">
        <i class="ri-share-forward-line"></i>
        分享
      </span>
      <div class="share-wrap">
        <i class="arrow"></i>
        <div class="share-icons">
          
          <a class="weibo share-sns" href="javascript:;" data-type="weibo">
            <i class="ri-weibo-fill"></i>
          </a>
          <a class="weixin share-sns wxFab" href="javascript:;" data-type="weixin">
            <i class="ri-wechat-fill"></i>
          </a>
          <a class="qq share-sns" href="javascript:;" data-type="qq">
            <i class="ri-qq-fill"></i>
          </a>
          <a class="douban share-sns" href="javascript:;" data-type="douban">
            <i class="ri-douban-line"></i>
          </a>
          <!-- <a class="qzone share-sns" href="javascript:;" data-type="qzone">
            <i class="icon icon-qzone"></i>
          </a> -->
          
          <a class="facebook share-sns" href="javascript:;" data-type="facebook">
            <i class="ri-facebook-circle-fill"></i>
          </a>
          <a class="twitter share-sns" href="javascript:;" data-type="twitter">
            <i class="ri-twitter-fill"></i>
          </a>
          <a class="google share-sns" href="javascript:;" data-type="google">
            <i class="ri-google-fill"></i>
          </a>
        </div>
      </div>
</div>

<div class="wx-share-modal">
    <a class="modal-close" href="javascript:;"><i class="ri-close-circle-line"></i></a>
    <p>扫一扫，分享到微信</p>
    <div class="wx-qrcode">
      <img src="" alt="微信分享二维码">
    </div>
</div>

<div id="share-mask"></div>  
    </footer>
  </div>

   
  <nav class="article-nav">
    
      <a href="/2020/07/30/%E4%BB%8EService-Workers%E8%AE%A4%E8%AF%86%E7%A6%BB%E7%BA%BF%E5%BA%94%E7%94%A8/" class="article-nav-link">
        <strong class="article-nav-caption">上一篇</strong>
        <div class="article-nav-title">
          
            从Service-Workers认识离线应用
          
        </div>
      </a>
    
    
      <a href="/2020/07/28/%E6%B7%B1%E5%85%A5%E6%B5%85%E5%87%BA-Webpack%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0%EF%BC%88%E4%B8%80%EF%BC%89/" class="article-nav-link">
        <strong class="article-nav-caption">下一篇</strong>
        <div class="article-nav-title">深入浅出-Webpack学习笔记（一）</div>
      </a>
    
  </nav>

   
<!-- valine评论 -->
<div id="vcomments-box">
  <div id="vcomments"></div>
</div>
<script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/valine@1.4.14/dist/Valine.min.js"></script>
<script>
  new Valine({
    el: "#vcomments",
    app_id: "2eBxdPB3eEwraN7IpwFckzeL-gzGzoHsz",
    app_key: "VGgCefQEluVxHdyMsm1Dpeih",
    path: window.location.pathname,
    avatar: "monsterid",
    placeholder: "评论一下我的文章吧~",
    recordIP: true,
  });
  const infoEle = document.querySelector("#vcomments .info");
  if (infoEle && infoEle.childNodes && infoEle.childNodes.length > 0) {
    infoEle.childNodes.forEach(function (item) {
      item.parentNode.removeChild(item);
    });
  }
</script>
<style>
  #vcomments-box {
    padding: 5px 30px;
  }

  @media screen and (max-width: 800px) {
    #vcomments-box {
      padding: 5px 0px;
    }
  }

  #vcomments-box #vcomments {
    background-color: #fff;
  }

  .v .vlist .vcard .vh {
    padding-right: 20px;
  }

  .v .vlist .vcard {
    padding-left: 10px;
  }
</style>

 
     
</article>

</section>
      <footer class="footer">
  <div class="outer">
    <ul>
      <li>
        Copyrights &copy;
        2015-2020
        <i class="ri-heart-fill heart_icon"></i> AURORA_ZXH
      </li>
    </ul>
    <ul>
      <li>
        
        
        
        Powered by <a href="https://hexo.io" target="_blank">Hexo</a>
        <span class="division">|</span>
        Theme - <a href="https://github.com/Shen-Yu/hexo-theme-ayer" target="_blank">Ayer</a>
        
      </li>
    </ul>
    <ul>
      <li>
        
        
        <span>
  <span><i class="ri-user-3-fill"></i>Visitors:<span id="busuanzi_value_site_uv"></span></s>
  <span class="division">|</span>
  <span><i class="ri-eye-fill"></i>Views:<span id="busuanzi_value_page_pv"></span></span>
</span>
        
      </li>
    </ul>
    <ul>
      
    </ul>
    <ul>
      <li>
        <!-- cnzz统计 -->
        
        <script type="text/javascript" src='https://s9.cnzz.com/z_stat.php?id=1278069914&amp;web_id=1278069914'></script>
        
      </li>
    </ul>
  </div>
</footer>
      <div class="float_btns">
        <div class="totop" id="totop">
  <i class="ri-arrow-up-line"></i>
</div>

<div class="todark" id="todark">
  <i class="ri-moon-line"></i>
</div>

      </div>
    </main>
    <aside class="sidebar on">
      <button class="navbar-toggle"></button>
<nav class="navbar">
  
  <div class="logo">
    <a href="/"><img src="/images/avatar.jpg" alt="AURORA"></a>
  </div>
  
  <ul class="nav nav-main">
    
    <li class="nav-item">
      <a class="nav-item-link" href="/">主页</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/archives">归档</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/categories">分类</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags">标签</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="http://aurora-zxh.lofter.com/" target="_blank" rel="noopener">随记</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/about">关于我</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/link">友链</a>
    </li>
    
  </ul>
</nav>
<nav class="navbar navbar-bottom">
  <ul class="nav">
    <li class="nav-item">
      
      <a class="nav-item-link nav-item-search"  title="Search">
        <i class="ri-search-line"></i>
      </a>
      
      
      <a class="nav-item-link" target="_blank" href="/atom.xml" title="RSS Feed">
        <i class="ri-rss-line"></i>
      </a>
      
    </li>
  </ul>
</nav>
<div class="search-form-wrap">
  <div class="local-search local-search-plugin">
  <input type="search" id="local-search-input" class="local-search-input" placeholder="Search...">
  <div id="local-search-result" class="local-search-result"></div>
</div>
</div>
    </aside>
    <script>
      if (window.matchMedia("(max-width: 768px)").matches) {
        document.querySelector('.content').classList.remove('on');
        document.querySelector('.sidebar').classList.remove('on');
      }
    </script>
    <div id="mask"></div>

<!-- #reward -->
<div id="reward">
  <span class="close"><i class="ri-close-line"></i></span>
  <p class="reward-p"><i class="ri-cup-line"></i>请我喝杯咖啡吧~</p>
  <div class="reward-box">
    
    <div class="reward-item">
      <img class="reward-img" src="/images/alipay.png">
      <span class="reward-type">支付宝</span>
    </div>
    
    
    <div class="reward-item">
      <img class="reward-img" src="/images/wxpay.png">
      <span class="reward-type">微信</span>
    </div>
    
  </div>
</div>
    
<script src="/js/jquery-2.0.3.min.js"></script>


<script src="/js/lazyload.min.js"></script>

<!-- Tocbot -->


<script src="/js/tocbot.min.js"></script>

<script>
  tocbot.init({
    tocSelector: '.tocbot',
    contentSelector: '.article-entry',
    headingSelector: 'h1, h2, h3, h4, h5, h6',
    hasInnerContainers: true,
    scrollSmooth: true,
    scrollContainer: 'main',
    positionFixedSelector: '.tocbot',
    positionFixedClass: 'is-position-fixed',
    fixedSidebarOffset: 'auto'
  });
</script>

<script src="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.css">
<script src="https://cdn.jsdelivr.net/npm/justifiedGallery@3.7.0/dist/js/jquery.justifiedGallery.min.js"></script>

<script src="/dist/main.js"></script>

<!-- ImageViewer -->

<!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">

    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>

    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">

        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>

        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">

            <div class="pswp__top-bar">

                <!--  Controls are self-explanatory. Order can be changed. -->

                <div class="pswp__counter"></div>

                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>

                <button class="pswp__button pswp__button--share" style="display:none" title="Share"></button>

                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>

                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                        <div class="pswp__preloader__cut">
                            <div class="pswp__preloader__donut"></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div>
            </div>

            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>

            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>

            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>

        </div>

    </div>

</div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/default-skin/default-skin.min.css">
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe-ui-default.min.js"></script>

<script>
    function viewer_init() {
        let pswpElement = document.querySelectorAll('.pswp')[0];
        let $imgArr = document.querySelectorAll(('.article-entry img:not(.reward-img)'))

        $imgArr.forEach(($em, i) => {
            $em.onclick = () => {
                // slider展开状态
                // todo: 这样不好，后面改成状态
                if (document.querySelector('.left-col.show')) return
                let items = []
                $imgArr.forEach(($em2, i2) => {
                    let img = $em2.getAttribute('data-idx', i2)
                    let src = $em2.getAttribute('data-target') || $em2.getAttribute('src')
                    let title = $em2.getAttribute('alt')
                    // 获得原图尺寸
                    const image = new Image()
                    image.src = src
                    items.push({
                        src: src,
                        w: image.width || $em2.width,
                        h: image.height || $em2.height,
                        title: title
                    })
                })
                var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, {
                    index: parseInt(i)
                });
                gallery.init()
            }
        })
    }
    viewer_init()
</script>

<!-- MathJax -->

<!-- Katex -->

<!-- busuanzi  -->


<script src="/js/busuanzi-2.3.pure.min.js"></script>


<!-- ClickLove -->

<!-- ClickBoom1 -->

<!-- ClickBoom2 -->

<!-- CodeCopy -->


<link rel="stylesheet" href="/css/clipboard.css">

<script src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"></script>
<script>
  function wait(callback, seconds) {
    var timelag = null;
    timelag = window.setTimeout(callback, seconds);
  }
  !function (e, t, a) {
    var initCopyCode = function(){
      var copyHtml = '';
      copyHtml += '<button class="btn-copy" data-clipboard-snippet="">';
      copyHtml += '<i class="ri-file-copy-2-line"></i><span>COPY</span>';
      copyHtml += '</button>';
      $(".highlight .code pre").before(copyHtml);
      $(".article pre code").before(copyHtml);
      var clipboard = new ClipboardJS('.btn-copy', {
        target: function(trigger) {
          return trigger.nextElementSibling;
        }
      });
      clipboard.on('success', function(e) {
        let $btn = $(e.trigger);
        $btn.addClass('copied');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-checkbox-circle-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPIED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-checkbox-circle-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
      clipboard.on('error', function(e) {
        e.clearSelection();
        let $btn = $(e.trigger);
        $btn.addClass('copy-failed');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-time-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPY FAILED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-time-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
    }
    initCopyCode();
  }(window, document);
</script>


<!-- CanvasBackground -->


    
  </div>
</body>

</html>